package com.traffic.managent.base;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.cxhome.cxinfox.cxuser.UserService;
import com.jfinal.core.Controller;
import com.traffic.managent.annotation.AutoBindModels;
import com.traffic.managent.config.CxHomeproperties;
import com.traffic.managent.model.system.Menu;
import com.traffic.managent.model.system.User;
import com.traffic.managent.util.Attr;
import com.traffic.managent.util.CxhomeUtils;
import com.traffic.managent.util.DateFormatUtils;
import com.traffic.managent.util.HandlerUtils;
import com.traffic.managent.util.StringUtils;

public class CxBaseController  extends Controller{

	protected static final String page_message = CxHomeproperties.getStr("PAGES.MESSAGE");
	protected static final Logger log = Logger.getLogger(CxBaseController.class);
	protected void renderMessage(String message) {
		renderMessage(message, "closeIframe();");
	}

	protected void renderMessageByFailed(String message) {
		renderMessage(message, "history.back();");
	}

	protected void renderMessage(String message, String obj) {
		String script = "";
		if (StringUtils.isEmpty(obj)) { // 关闭页面
			script = "closeIframe();";
		} else if (script.endsWith(".jsp")) { // 页面跳转
			script = "window.location.href = \"" + obj + "\"";
		} else { // 直接执行JS
			script = obj;
		}
		setAttr("msg", message);
		setAttr("script", script);
		render(page_message);
	}

	protected void render500(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.getRequestDispatcher("/pages/error/500.jsp").forward(request, response);
		} catch (Exception e) {
			log.error("500 page -->", e);
		}
	}

	/**
	 * 获取前一个页面
	 * 
	 * @return
	 */
	protected String getPrePage() {
		return getRequest().getHeader("Referer");
	}

	/**
	 * 获取当前时间，保存创建时间使用
	 * 
	 * @return
	 */
	protected String getNow() {
		return DateFormatUtils.getNow(DateFormatUtils.DEFAULT_REGEX_YYYY_MM_DD_HH_MIN_SS);
	}

	protected <T> T handler(Class<T> modelClass) {
		Object o = null;
		try {
			o = modelClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return handler(o);
	}

	@SuppressWarnings("unchecked")
	protected <T> T handler(Object o) {
		if (o == null) {
			return null;
		}
		return (T) HandlerUtils.handler(getRequest(), o);
	}

	public void renderAuto(String view) {
		String path = getAutoPath(view);

		super.render(path);
	}

	public void redirectAuto(String view) {
		String path = getAutoPath(view);

		super.redirect(path);
	}

	protected String getAutoPath(String view) {
		String path = view;

		if (!view.startsWith("/")) {
			path = "/" + path;
		}

		path = (isMoblie() ? Attr.PATH_MOBILE : Attr.PATH_PC) + path;

		if (view.startsWith("/")) {
			path = "/" + path;
		}

		path = path.replace("//", "/");
		return path;
	}

	public boolean isMoblie() {
		return getSessionAttr(Attr.SESSION_IS_MOILE);
	}

	@SuppressWarnings("rawtypes")
	public SessionUser getSessionUser() {
		User sysUser = getSessionAttr(Attr.SESSION_NAME);
		try {
			// 如果session没有，cookie有~那么就设置到Session
			if (sysUser == null) {
				String cookieContent = getCookie(Attr.SESSION_NAME);
				if (cookieContent != null) {
					String key = CxhomeUtils.cookieDecrypt(cookieContent);
					if (StringUtils.isNotEmpty(key) && key.split(",").length == 2) {
						String userid = key.split(",")[0];
						String password = key.split(",")[1];
						sysUser = User.dao.findFirstByWhere(" where ids = ? and password = ? ", userid, password);
						if (sysUser != null)
							setSessionUser(sysUser);
					}
				}
			}
		} catch (Exception e) {
			// 异常cookie重新登陆
			removeSessionAttr(Attr.SESSION_NAME);
			removeCookie(Attr.SESSION_NAME);

			log.error("cooke user异常:", e);
			return null;
		}
		return sysUser;
	}

	@SuppressWarnings("rawtypes")
	public SessionUser setSessionUser(SessionUser sessionuser) {
		setSessionAttr(Attr.SESSION_NAME, sessionuser);
		// 设置cookie，用id+password Encrypt
		User user = (User) sessionuser;
		String key = user.getUseriD() + "," + user.getStr("username");

		String cookieContent = CxhomeUtils.cookieEncrypt(key);
		setCookie(Attr.SESSION_NAME, cookieContent, 7 * 24 * 60 * 60);

		// 设置菜单权限
		Map<String, List<Menu>> map = UserService.service.getAuthMap(user);
		// 注入菜单
		setSessionAttr("menuCx", map);

		// 不能访问的菜单
		setSessionAttr("nomenuCx", UserService.service.getNoAuthMap(map));

		return user;
	}

	public void removeSessionUser() {
		removeSessionAttr(Attr.SESSION_NAME);
		// 删除cookie
		removeCookie(Attr.SESSION_NAME);
	}

	public Paginator getPaginator() {
		Paginator paginator = new Paginator();
		Integer pageNo = getParaToInt("pageNo");
		if (pageNo != null && pageNo > 0) {
			paginator.setPageNo(pageNo);
		}
		Integer pageSize = getParaToInt("recordsperpage");
		if (pageSize != null && pageSize > 0) {
			paginator.setPageSize(pageSize);
		}
		return paginator;
	}

	public Object[] toArray(List<Object> list) {
		return list.toArray(new Object[list.size()]);
	}

	public BaseForm getBaseForm() {
		BaseForm form = super.getAttr("form");
		return form == null ? new BaseForm() : form;
	}

	/**
	 * 原始的GetModel方法
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByOld(Class<T> modelClass) {
		return super.getModel(modelClass);
	}

	/**
	 * 覆盖原始方法，采用PAGE_MODEL_NAME做为前缀
	 */
	@Override
	public <T> T getModel(Class<T> modelClass) {
		return super.getModel(modelClass, Attr.PAGE_MODEL_NAME);
	}

	/**
	 * 新GetModel方法，采用PAGE_ATTR_NAME，作为前缀
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByAttr(Class<T> modelClass) {
		return super.getModel(modelClass, Attr.PAGE_ATTR_NAME);
	}

	/**
	 * 新GetModel方法，采用PAGE_FORM_NAME，作为前缀
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByForm(Class<T> modelClass) {
		return super.getModel(modelClass, Attr.PAGE_FORM_NAME);
//		return super.getBean(modelClass, Attr.PAGE_FORM_NAME);
	}
	
	
}
